<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/11/4
 * Time: 9:37
 */
namespace App\Http\Controllers\admin_system;

use App\Http\Controllers\Weixin\WeixinServiceController;
use App\Models\V1\MemberModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Module\EntWithdrawMoneyLog;
use App\Module\EntMemberDRP;
use Storage;
use Cookie;
use DB;
use Validator;
use Redirect;
use Session;

class PartnerController extends Controller
{
    public function index(Request $request,$keyword = '')
    {
        $status     =   $request->input('status',0);
        $db = DB::table('vw_withdrawmoneylog')
            ->select('WiMoID', 'mYourName', 'UserName', 'InvoiceTitle', 'YourName', 'CardNo', 'BankName', 'WithdrawMoney', 'States', 'DeleteMark', 'ReleaseDate', 'AddDate')
            ->where('DeleteMark', '1')
            ->where('States', $status);
        if($keyword)
        {
            $db->where(function ($query) use ($keyword) {
            $query->orwhere('mYourName', 'like', '%' . $keyword . '%')
                ->orwhere('YourName', 'like', '%' . $keyword . '%')
                ->orwhere('UserName', 'like', '%' . $keyword . '%');
            });
        }

        $moneyLogs = $db->orderBy('ReleaseDate', 'desc')
        ->paginate(20);
        return view('admin_system.partner.index', [
            'withdrawmoneylog' => $moneyLogs,
            'keyword' => $keyword
        ]);
    }


    public function indexedit($id)
    {
        $entWithdrawMoneyLog = EntWithdrawMoneyLog::findOrFail($id);
        $withdrawStates = [
            ['key'=>1,'name'=>'成功'],
            ['key'=>2,'name'=>'失败']
        ];
        return view('admin_system.partner.indexEdit', [
            'entWithdrawMoneyLog'   => $entWithdrawMoneyLog,
            'types'                 => $withdrawStates
        ]);
    }

    //rsa加密响应字段
    public function rsa_encrypt($str)
    {
        $pem    = dirname(app_path('')).'/zhengshu/rsa/public.pem';
        $pu_key = openssl_pkey_get_public(file_get_contents($pem));  //读取公钥内容
        $encryptedBlock = '';
        $encrypted = '';
        // 用标准的RSA加密库对敏感信息进行加密，选择RSA_PKCS1_OAEP_PADDING填充模式
        //   （eg：Java的填充方式要选 " RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING"）
        // 得到进行rsa加密并转base64之后的密文
        openssl_public_encrypt($str,$encryptedBlock,$pu_key,OPENSSL_PKCS1_OAEP_PADDING);
        $str_base64  = base64_encode($encrypted.$encryptedBlock);
        return $str_base64;
    }


    public function indexupdate(Request $request, $id)
    {
        $drawMoneyLog    = EntWithdrawMoneyLog::find($id);
        if($drawMoneyLog->States != 0)
        {
            return apiData()->notice('订单已经审核过');
        }

        $states          = trim($request->get('TypeIDSelect'));
        $remark          = trim($request->get('txtWithdrawRemark'));

        $drawMoneyLog->WithdrawRemark   = $remark;
        $drawMoneyLog->States           = $states;

        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_member_number($drawMoneyLog->MemNumber);



        if ($states == 2) //取消提现的申请
        {
            //返还提现金额到分会学习官系统表
            if($drawMoneyLog->MemType == 'clo')
            {
                $table  = "chapter_drp";

            }elseif($drawMoneyLog->MemType == 'prisident') {

                $table  = "chapter_prisident";
            }

            $sql = "UPDATE $table SET can_draw_money = can_draw_money + $drawMoneyLog->WithdrawMoney
                    WHERE user_id = $memberInfo->UserID and is_delete = 0";
            DB::update($sql);

            $drawMoneyLog->save();
            return apiData()->notice('操作完成');
        }



        $weixinService  = new WeixinServiceController();
        $app            = $weixinService->get_weixin_app();
        $tradeNo        = create_member_number();
        $payResult      = false;


        //计算手续费
        $serviceCharge  = $drawMoneyLog->WidthdrawMoney * 0.001 ;
        $serviceCharge  = $serviceCharge < 1 ? 1 : $serviceCharge;
        $serviceCharge  = $serviceCharge > 25? 25: $serviceCharge;
        $realPay        = ($drawMoneyLog->WithdrawMoney - $serviceCharge) * 100;


        if($drawMoneyLog->BankName =='微信')//微信转账
        {
            $merchantpay    = $app->merchant_pay;
            $merchantPayData = [
                'partner_trade_no'  => $tradeNo, //随机字符串作为订单号，跟红包和支付一个概念。
                'openid'            => $drawMoneyLog->CardNo, //收款人的openid
                'check_name'        => 'NO_CHECK',  //文档中有三种校验实名的方法 NO_CHECK OPTION_CHECK FORCE_CHECK
                're_user_name'      => $memberInfo->YourName,     //OPTION_CHECK FORCE_CHECK 校验实名的时候必须提交
                'amount'            => $realPay,  //单位为分
                'desc'              => $memberInfo->YourName."提现",
                'spbill_create_ip'  => get_real_ip()
            ];
            $result         = $merchantpay->send($merchantPayData);
            if($result->result_code == 'SUCCESS')
            {
                $paymentNo  = $result->payment_no;
                $payResult  = true;
            }

        } else { //转账到银行卡

            $merchantPay    = $app->merchant_pay;
            $bankInfo       = DB::table('paycard')
                ->where('CardNo',$drawMoneyLog->CardNo)
                ->where('DeleteMark',1)
                ->first();

            $merchantPayData = [
                'partner_trade_no'  => $tradeNo,
                "enc_bank_no"       => $this->rsa_encrypt($drawMoneyLog->CardNo),
                "enc_true_name"     => $this->rsa_encrypt($drawMoneyLog->YourName),
                "bank_code"         => $bankInfo->WeiXinCardNo,
                'amount'            => $realPay,
                'desc'              => $memberInfo->YourName."提现",
            ];

            $paymentNo  = create_member_number();
            $payResult  = true;

            $result     = $merchantPay->send_to_bank($merchantPayData);
            if($result->result_code == 'SUCCESS')
            {
                $paymentNo  = $result->payment_no;
                $payResult  = true;
            }
        }

        if($payResult)
        {

            $drawMoneyLog->PaymentNo        = $paymentNo;
            $drawMoneyLog->TradeNo          = $tradeNo;
            $drawMoneyLog->save();
        }
        return apiData()->notice($result->return_msg);
    }
}